import axios from 'axios';
import qs from 'qs';
import vue from 'vue';
if(window.location.port){
  axios.defaults.baseURL='/api';
}else{
  axios.defaults.baseURL='';
}
axios.defaults.timeout=5000;
import store from '@/vuex/index';
import router from '@/libs/router';
let loadingNum=0;
let loadingTimeOut = null;
import { Indicator } from 'mint-ui';
let  loading = true;

axios.interceptors.request.use(config=>{
	if(config.url.indexOf("lastplay")>-1){
		//loadingNum++;
		return config;
	}
  /*if(config.isLoad!='noload'){
    Indicator.open({
      text: '加载中...',
      spinnerType: 'fading-circle'
    });
  }*/

  loadingNum++;
  return config;
});
axios.interceptors.response.use(function (res){
  let key=res.headers.authorization;
  if (key){
    localStorage.setItem('token',key);
  }
  return res;
},function(error){
  // Do something with res error
  return Promise.reject(error);
});
const fetch=(opts,data,isLoad) => {
  let httpDefaultOpts={ //http默认配置
    method:opts.method,
    url:opts.url,
    timeout:10000,
    isLoad:isLoad,
    params:data,
    data:qs.stringify(data),
    headers:opts.method == 'get' ? {
      'X-Requested-With': 'XMLHttpRequest',
      "Accept": "application/json",
      "Content-Type": "application/json; charset=UTF-8"
    } : {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
  };

  if(opts.method=='get'){
    delete httpDefaultOpts.data;
  }else{
    delete httpDefaultOpts.params;
  }

  let promise=new Promise((resolve,reject)=>{
    axios(httpDefaultOpts).then(
      (res)=>{
        loadingNum--;
        switch(parseInt(res.data.ret,10)){
          case 0:
            resolve(res);
            break;
          case 2003:
            resolve(res);
            break;
          case 4001:
            Toast(res.data.msg);
            setTimeout(()=>{
              router.replace({name:'home'});
            },1000);
            break;
          case 2000:
            if(isLoad!='noLogin'){
              router.push({name:'login'});
            }else{
              resolve(res);
            };
            break;
          default:
            Toast(res.data.msg);
        }
        if(loadingNum<=1){
          Indicator.close();
        }
      }
    ).catch(
      res=>{
        reject(res);
        Indicator.close();
      }
    )
  });

  promise.setLoading=flag=>{
    loading=flag;
  };
  return promise
};


export default fetch;
